'''
YahooFinance utility to retrieve historical daily data and current data from YahooFinance.

Created on April, 2012
@author: bruce
'''

from httplib import HTTPConnection

from logutil import LogFile

class YahooFinance:
    def __init__(self):  
        self.__log = LogFile("test", 'YahooDataCollect')
        self.__log.detail_log('Normal', 'Start of Yahoo! Finance data collection!')
        
        self.__histConn = HTTPConnection('ichart.yahoo.com')
        self.__log.detail_log('Normal', 'Historical quotes connection established!')
        self.__currentConn = HTTPConnection('download.finance.yahoo.com')
        self.__log.detail_log('Normal', 'Daily quotes connection established!')         
    
    """
    Get historical daily quotes from yahoo API
    Reference: http://code.google.com/p/yahoo-finance-managed/wiki/csvHistQuotesDownload
    """
    def gethistquotes(self, symbol, fromDate=None, toDate=None, interval=None):        
        requestVal = "/table.csv?s=" + symbol
        # Note that according to the yahoo API, the url takes the value of the requested month as 1 less.
        if fromDate != None:
            requestVal += ('&a=%(month)s&b=%(day)s&c=%(year)s' 
                           %{'month' : str(fromDate[0] - 1), 'day' : str(fromDate[1]), 'year' : str(fromDate[2])})            
        if toDate != None:
            requestVal += ('&d=%(month)s&e=%(day)s&f=%(year)s' 
                           %{'month' : str(toDate[0] - 1), 'day' : str(toDate[1]), 'year' : str(toDate[2])})        
        return self._getyahooquote(self.__histConn, requestVal, symbol)

    """
    Get current quote from yahoo API
    Reference: http://code.google.com/p/yahoo-finance-managed/wiki/csvQuotesDownload
    """
    def getcurrentquote(self, symbols, properties='n0s0d1o0h0g0l1p0v0'): 
        # n0: Name, s0: Symbol, d1: Last Trade Date, o0: Open, h0: High, g0: Low, l1: Last Trade Price, p0: Last close, v0: Volume
        if isinstance(symbols, (list, tuple)):
            symbols = ','.join(symbols)            
        requestVal = '/d/quotes.csv?s=' + symbols + '&f=' + properties
        self.__log.detail_log("Normal", "request Val = " + requestVal)
        
        return self._getyahooquote(self.__currentConn, requestVal, symbols)  
            
    """
    Uninitialize the class by close the connections. 
    """
    def uninitialize(self):
        self.__histConn.close()
        self.__currentConn.close()
        self.__log.closelog()
        
    def _getyahooquote(self, httpConn, requestVal, symbols):
        max_count = 5
        count = 0
        response_str = ''
        while count < max_count:
            count += 1
            self.__log.detail_log('Normal', 'try times: ' + str(count) + ' ' + str(symbols))
            httpConn.request('GET', requestVal)   # Reference for the properties: http://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty            
            response = httpConn.getresponse()
            status_code = response.status
            if status_code >= 200 and status_code < 300: # Successful http status code
                response_str = response.read()            
                break                        
        # return an empty string if we fail to get any response.
        return response_str 


if __name__ == "__main__": 
    stockQuotes = YahooFinance()
    googHistQuotes = stockQuotes.gethistquotes('GOOG', (3, 20, 2012), (4, 20, 2012))
    print googHistQuotes
    googQuotes = stockQuotes.getcurrentquote('GOOG')
    print googQuotes
    googQuotes = stockQuotes.getcurrentquote(('GOOG','MSFT'))
    print googQuotes
    
    histQuotes = stockQuotes.gethistquotes('GOOG', (4, 25, 2012))
    print histQuotes
    histQuotes = stockQuotes.gethistquotes('GOOG', (4, 27, 2012))
    print histQuotes
    histQuotes = stockQuotes.gethistquotes('GOOG', (4, 28, 2012))
    print histQuotes
    histQuotes = stockQuotes.gethistquotes('GOOG', (4, 29, 2012))
    print histQuotes
    histQuotes = stockQuotes.gethistquotes('GOOG', (4, 30, 2012))
    print histQuotes
    
    stockQuotes.uninitialize()